import axios from 'axios'
import bridge from './bridge'

const service = axios.create({
    baseURL: bridge.getBaseUrl(), // 动态获取
    timeout: 10000
})

service.interceptors.request.use(
    config => {
        config.headers.token = bridge.getCacheModel().token;
        config.headers.tenant_id = bridge.getCacheModel().tenantId;
        config.headers.language = bridge.getLanguage();
        config.headers.timezone = bridge.getTimezone();
        config.headers.device_type = "POS";
        config.headers.version = bridge.getVersion();

        const commonData = {
            language:  bridge.getLanguage(),
            deviceInfo: bridge.getDeviceId()
        }

        if (config.method === 'get') {
            config.params = Object.assign(config.params || {}, commonData)
        }

        if (config.method === 'post') {
            config.data = Object.assign(config.data || {}, commonData)
        }

        return config
    },
    error => Promise.reject(error)
)

service.interceptors.response.use(
    res => {
        if (!res.data.success) {
            console.error(res.data.message || '请求失败')
            return Promise.reject(res.data)
        }
        return res.data
    },
    error => {
        console.error('网络异常', error)
        return Promise.reject(error)
    }
)

export default service
